package org.uned.agonzalo16.bitacora.web.comment;

import java.util.Date;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.uned.agonzalo16.bitacora.dao.ArticleDao;
import org.uned.agonzalo16.bitacora.dao.CommentDao;
import org.uned.agonzalo16.bitacora.dao.UserDao;
import org.uned.agonzalo16.bitacora.domain.Comment;
import org.uned.agonzalo16.bitacora.service.security.AuthenticatedUser;

@RequestMapping("/comment")
@Controller
@SessionAttributes({ "userAttribute" })
public class CommentController {

	@Autowired
	private ArticleDao articleDao;

	@Autowired
	private CommentDao commentDao;

	@Autowired
	private UserDao userDao;

	@RequestMapping(method = RequestMethod.POST, value = "/create")
	public String create(@Valid @ModelAttribute("article") CommentForm form, BindingResult result, @ModelAttribute("userAttribute") AuthenticatedUser user) {

		if (result.hasErrors()) {
			return "contributor/article/create";
		}

		Comment comment = new Comment();
		comment.setContent(form.getContent());
		comment.setCreationDate(new Date());
		comment.setArticle(articleDao.get(form.getArticleId()));
		comment.setUser(userDao.get(user.getId()));

		commentDao.merge(comment);

		return "redirect:/article/" + form.getArticleId();
	}
}
